/**
 * 简版的promsie
 * @param {function} fn  一般写法（resolve,reject)=>{} 
 */
function myPromise(fn) {
  const that = this // this指向实例化后的新对象
  that.state = 'pending' // promise状态
  that.value = null  // resolve 或 reject传入的参数
  that.resovleCallbacks = [] // resovle 回调函数
  that.rejectClasbacks = [] // reject 回调函数
  
  // 对传入函数进行处理
  try {
    // 调用对应的resolve,reject处理函数
    fn(resolve, reject)
  } catch (e) { // 执行错误捕获
    reject(e)
  }

  // resolve 函数
  function resolve(value) {
    // console.log('resolve 参数value:', value) 
    if (that.state == 'pending') {
      // 模拟状态变更为resolved
      that.state = 'resolved' // 更改promise状态
      that.value = value
      that.resovleCallbacks.map( cb => cb(that.value))
      // console.log('resovleCallbacks', that.resovleCallbacks)
    }
  }

  // reject函数
  function reject(value) {
    if (that.state == 'pending') {
      that.state = 'rejected'
      that.value = value
      that.rejectClasbacks.map( cb => cb(that.value))
    }
  }
}

/**
 * 在promise原型上注册方法then
 * 对then进行处理, onFulfilled, onRejected 是.then的两个回调参数
 */
// 
myPromise.prototype.then = function(onFulfilled, onRejected) {
  console.log('then第一个参数：onFulfilled', onFulfilled)
  console.log('---------')
  const that = this
  // 参数是否是函数，不是函数穿件函数并赋值
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
  console.log('onFulfilled ', onFulfilled )
  onRejected = typeof onRejected  === 'function' ? onRejected : r => { throw r }
  console.log('onRejected ', onRejected )

  if (that.state === 'pending') {
    that.resovleCallbacks.push(onFulfilled)
    that.rejectClasbacks.push(onRejected)
  }

  // 当状态从pending变为resolved 时执行onfFullfilled回调函数
  if(that.state === 'resolved') {
    onFulfilled(that.value)
  }

  // 当状态从pending变为rejected 时执行onRejected回调函数
  if(that.state === 'rejected') {
    onRejected(that.value)
  }
}

// 实例化构造函数
let p = new myPromise((resolve, reject) => {
  setTimeout(()=>{
    resolve(66666)
  }, 0)
  // reject(234)
})
console.log('promises实例结果：', p)
console.log('---------')
// promise 初始化结果为
// myPromise {
//   state: 'pending', 状态
//   value: null, resolve 或 reject传入的参数
//   resovleCallbacks: [], 
//   rejectClasbacks: [] 
// }

// 调用的是原型链是方法then
p.then(value => {
  console.log('.then成功输出结果：', value)
}, err => {
  console.log('.catch成功输出结果', err)
})
{
  let a = 1
  let b = 2
  console.log('11', a)
}
// console.log('a', a)